package com.drcoffee.drcoffeemall.service.impl;

import com.drcoffee.drcoffeemall.entry.Address;
import com.drcoffee.drcoffeemall.entry.Result;
import com.drcoffee.drcoffeemall.entry.User;
import com.drcoffee.drcoffeemall.mapper.AddressMapper;
import com.drcoffee.drcoffeemall.mapper.UserMapper;
import com.drcoffee.drcoffeemall.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.tokenize.SimpleTokenizer;
import opennlp.tools.util.Span;
import org.apache.el.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class AddressServiceImpl implements AddressService {
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;


    private NameFinderME nameFinder;

    private SimpleTokenizer tokenizer;

    /*
     * 添加收件地址
     * */
    public Result addAddress(String Token, Address address) {
        User user = (User) redisTemplate.opsForValue().get(Token);
        try {
            Integer length = addressMapper.getAddressCountByAccount(address.getUser_account());
            if (length > 50) {
                return new Result(2, "SUCCESS", "The number of addresses that can be added exceeds the limit", null);
            } else {
                // 查询默认地址
                Integer defaultAddressID = userMapper.getDefaultAddressID(user.getAccount());

                if (user.getPermission_id()!=2){
                    String pc = address.getProvince_code();
                    if(pc.length() < 6){
                        int gets1 = 6 - pc.length();
                        StringBuilder stringBuilder = new StringBuilder(pc);
                        for (int i = 0; i < gets1; i++){
                            stringBuilder.append('0');
                        }
                        pc = stringBuilder.toString();
                    }
                    address.setProvince_code(pc);

                    String ct = address.getCity_code();
                    if (ct.length()< 6){
                        int gets2 = 6 - ct.length();
                        StringBuilder stringBuilder1 = new StringBuilder(ct);
                        for (int i = 0; i < gets2; i++){
                            stringBuilder1.append('0');
                        }
                        ct = stringBuilder1.toString();
                    }
                    address.setCity_code(ct);
                }

                addressMapper.addAddress(address);
                if (defaultAddressID == null) {
                    // 设置为默认地址
                    userMapper.setDefaultAddress(address.getId(), address.getUser_account());
                }
                return new Result(1, "SUCCESS", "Adding address succeeded", address.getId());
            }
        } catch (Exception e) {
            log.error("===================== addAddress()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    /*
     * 删除地址
     * */
    @Override
    public Result deleteAddress(Integer id, String account) {
        try {
            // 判断地址是否为默认
            User user = userMapper.getUserByAccount(account);
            if (Objects.equals(user.getDefault_address(), id)) {
                return new Result(2, "SUCCESS", "The current address is the default address! Unable to delete", null);
            } else {
                addressMapper.deleteAddress(id);
                return new Result(1, "SUCCESS", "Deleting the address succeeded", null);
            }
        } catch (Exception e) {
            log.error("===================== deleteAddress()异常： =====================", e);
            return new Result(1, "ERROR", e.getMessage(), null);
        }
    }

    /*
     * 修改地址
     * */
    @Override
    public Result updateAddress(Address address) {
        try {
            addressMapper.updateAddress(address);
            return new Result(1, "SUCCESS", "Succeeded in modifying the address", null);
        } catch (Exception e) {
            log.error("===================== updateAddress()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    /*
     * 根据账号查询收件地址
     * */
    @Override
    public Result getAddressByAccount(String account) {
        try {
            List<Address> addressList = addressMapper.getAddressByAccount(account);
            return new Result(1, "SUCCESS", "Address query succeeded", addressList);
        } catch (Exception e) {
            log.error("===================== getAddressByAccount()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    /*
     * 根据Id查询收件地址(查询默认地址)
     * */
    @Override
    public Result getAddressById(Integer id) {
        try {
            Address address = addressMapper.getAddressById(id);
            return new Result(1, "SUCCESS", "", address);
        } catch (Exception e) {
            log.error("===================== getAddressById()异常： =====================", e);
            return new Result(1, "SUCCESS",e.getMessage(), null);
        }
    }

    /**
     * 自动识别地址方法
     * @param autoText
     * @return
     */
    @Override
    public Result autoAddress(String autoText) {
        Address addressInfo = new Address();
        try {
            Pattern phonePattern = Pattern.compile("\\d{11}");
            Matcher phoneMatcher = phonePattern.matcher(autoText);
            if (phoneMatcher.find()) {
                addressInfo.setPhone(phoneMatcher.group().substring(0, 3) + " " + phoneMatcher.group().substring(3, 7) + " " + phoneMatcher.group().substring(7));
            }

            String regex="(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<county>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
            Matcher m = Pattern.compile(regex).matcher(autoText);

            if(m.find()){
                String province = m.group("province").replaceAll("[,.;，。\\d]+","");
                if (province.contains("内蒙古自治区")){
                    String last1 = province.substring(province.length() - 6);
                    addressInfo.setProvince(last1);
                }else if (province.contains("广西壮族自治区") || province.contains("宁夏回族自治区")){
                    String last2 = province.substring(province.length() - 7);
                    addressInfo.setProvince(last2);
                }else if (province.contains("西藏自治区")){
                    String last3 = province.substring(province.length() - 5);
                    addressInfo.setProvince(last3);
                }else if (province.contains("新疆维吾尔自治区")){
                    String last4 = province.substring(province.length() - 8);
                    addressInfo.setProvince(last4);
                }else if (province.contains("黑龙江省")){
                    String last5 = province.substring(province.length() - 4);
                    addressInfo.setProvince(last5);
                } else {
                    String last = province.substring(province.length() - 3);
                    addressInfo.setProvince(last);
                }
                addressInfo.setCity(m.group("city").replaceAll("[,.;，。？?\\s]", ""));
                String county = m.group("county").replaceAll("[,.;，。？?\\s]", "");
                int index = county.indexOf("区");
                if (index != -1) {
                    String region = county.substring(0, index + 1);
                    addressInfo.setRegion(region);
                } else {
                    addressInfo.setRegion(m.group("county").replaceAll("[,.;，。？?]", ""));
                }
            }
            String[] parts = autoText.split("\\d{11}|省|市|区|县|镇|乡|村|庄|场|街|路|街口|号|村道|弄|里|号牌|弄堂|弄口|弄旁|弄内|号内|弄旁|弄内|号牌|弄堂|弄口|弄旁|弄内|号牌|弄堂|弄口|弄旁|弄内|号牌|弄堂|弄口|弄旁|弄内|号牌|弄堂|弄口|弄旁|弄内|号牌|弄堂|弄口|弄旁|弄内|号牌|弄堂|弄口|弄旁|弄内|号牌|弄堂|弄口|弄旁|弄内|号牌|弄堂|弄口|弄旁|弄内");
            String name = parts[parts.length - 1].trim();
            name = name.replaceAll("[,.;，。？?]", "");
            addressInfo.setRecipients(name);
//            System.out.println("获取到的省市区"+ "111"+addressInfo.getProvince()+"222"+addressInfo.getCity()+"333"+addressInfo.getRegion());
//            String[] parts1 = autoText.split("\\d{11}|省|市|区");
//            StringBuilder address = new StringBuilder();
//            for (String part : parts1) {
//                System.out.println("获取到字符串中的值为"+part);
//                address.append(parts[parts1.length- 1].trim());
//            }

//            if (parts1.length > 0) {
//                String lastPart = parts1[parts1.length - 1];
//                address.append(lastPart.trim());
//            }
            String finalAddress = autoText.substring(autoText.indexOf("区") + 1).trim();
            finalAddress = finalAddress.replaceAll("\\d{11}", "").replace(name, "").trim();
//            String finalAddress = address.toString().trim().replaceAll("[,.);，。？?]", "");
            addressInfo.setAddress(finalAddress);
            System.out.println("999999999999999"+addressInfo.getAddress()+"555"+addressInfo.getPhone()+"---"+addressInfo.getRecipients());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(1, "SUCCESS", "", addressInfo);
    }


}
